package com.clb.studyproject.ui

import android.graphics.*
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.clb.studyproject.R
import java.net.URL

class AddWatermarkToPicActivity : AppCompatActivity(R.layout.activity_add_watermark_to_pic) {

    private lateinit var imgShow: ImageView
    private val picUrl = "https://img1.baidu.com/it/u=3102336817,2216289337&fm=26&fmt=auto&gp=0.jpg"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        imgShow = findViewById(R.id.img_show)
        addWatermarkToPic()
    }

    private fun addWatermarkToPic() {

        Thread {
            //获取网络图片Bitmap
            val url = URL(picUrl)
            val openStream = url.openStream()
            val picBitmap = BitmapFactory.decodeStream(openStream)
            openStream.close()

            //生成文字水印Bitmap
            val paint = Paint()
            //抗锯齿
            paint.isAntiAlias = true
            paint.textSize = 15F
            paint.color = Color.WHITE

            val fontMetricsInt = paint.fontMetricsInt
            val width = paint.measureText(packageName).toInt()
            val height = fontMetricsInt.descent - fontMetricsInt.ascent

            val createBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(createBitmap)
            canvas.drawText(packageName, 0F, (fontMetricsInt.leading - fontMetricsInt.ascent).toFloat(), paint)
            canvas.save()

            //合成两个Bitmap
            val picWidth = picBitmap.width
            val picHeight = picBitmap.height
            val createBitmap1 = Bitmap.createBitmap(picWidth, picHeight, Bitmap.Config.ARGB_8888)
            val canvas1 = Canvas(createBitmap1)
            //在左上角绘制
            canvas1.drawBitmap(picBitmap, 0F, 0F, null)
            canvas1.drawBitmap(createBitmap, picWidth - 10F - width, picHeight - 10F - height, null)
            canvas1.save()
            canvas1.restore()

            runOnUiThread {
                imgShow.setImageBitmap(createBitmap1)
            }
        }.start()
    }
}
